from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
                             QLineEdit, QPushButton, QMessageBox)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QIcon, QPixmap
from db.db_util import DBUtil
from ui.register_dialog import RegisterDialog  # 导入注册窗口

class LoginDialog(QDialog):
    """登录窗口"""
    login_success = pyqtSignal(str, str)  # 登录成功信号（用户名，角色）

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("点云处理系统 - 登录")
        self.setFixedSize(400, 300)
        # 新增 Qt.WindowCloseButtonHint，显示关闭按钮
        self.setWindowFlags(Qt.Window | Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint)
        self.init_ui()

    def init_ui(self):
        """初始化界面"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(30, 30, 30, 30)
        main_layout.setSpacing(20)

        # 图标
        icon_label = QLabel()
        icon_label.setAlignment(Qt.AlignCenter)
        icon = QIcon.fromTheme("cloud", QIcon("point_cloud_icon.png"))  # 可替换为自定义图标
        pixmap = icon.pixmap(80, 80)
        icon_label.setPixmap(pixmap)
        main_layout.addWidget(icon_label)

        # 用户名输入
        username_layout = QHBoxLayout()
        username_label = QLabel("用户名：")
        username_label.setStyleSheet("color: white; font-size: 14px;")
        self.username_edit = QLineEdit()
        self.username_edit.setPlaceholderText("请输入用户名")
        self.username_edit.setStyleSheet("""
            QLineEdit {
                padding: 8px; border: 1px solid #666; border-radius: 5px;
                background-color: #333; color: white;
            }
            QLineEdit:focus { border-color: #4CAF50; outline: none; }
        """)
        username_layout.addWidget(username_label)
        username_layout.addWidget(self.username_edit)
        main_layout.addLayout(username_layout)

        # 密码输入
        password_layout = QHBoxLayout()
        password_label = QLabel("密  码：")
        password_label.setStyleSheet("color: white; font-size: 14px;")
        self.password_edit = QLineEdit()
        self.password_edit.setPlaceholderText("请输入密码")
        self.password_edit.setEchoMode(QLineEdit.Password)
        self.password_edit.setStyleSheet("""
            QLineEdit {
                padding: 8px; border: 1px solid #666; border-radius: 5px;
                background-color: #333; color: white;
            }
            QLineEdit:focus { border-color: #4CAF50; outline: none; }
        """)
        password_layout.addWidget(password_label)
        password_layout.addWidget(self.password_edit)
        main_layout.addLayout(password_layout)

        # 登录按钮
        login_btn = QPushButton("登录")
        login_btn.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50; color: white; font-size: 16px;
                font-weight: bold; padding: 10px; border-radius: 5px; border: none;
            }
            QPushButton:hover { background-color: #45a049; }
            QPushButton:pressed { background-color: #3d8b40; }
        """)
        login_btn.clicked.connect(self.handle_login)
        main_layout.addWidget(login_btn, alignment=Qt.AlignCenter)

        # 新增：注册按钮（在登录按钮下方）
        register_btn = QPushButton("注册新账号")
        register_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent; color: #2196F3; font-size: 14px;
                border: none; text-decoration: underline;
            }
            QPushButton:hover { color: #1976D2; }
        """)
        register_btn.clicked.connect(self.show_register_dialog)
        main_layout.addWidget(register_btn, alignment=Qt.AlignCenter)

        # 窗口背景
        self.setStyleSheet("background-color: #2b2b2b;")

    def handle_login(self):
        """处理登录逻辑"""
        username = self.username_edit.text().strip()
        password = self.password_edit.text().strip()

        # 输入校验
        if not username or not password:
            QMessageBox.warning(self, "警告", "用户名和密码不能为空！")
            return

        # 查询用户
        user = DBUtil.query_user(username)
        if not user:
            QMessageBox.critical(self, "错误", "用户名不存在或账号已禁用！")
            return

        # 验证密码
        if not DBUtil.verify_password(password, user['password_hash']):
            QMessageBox.critical(self, "错误", "密码输入错误！")
            return

        # 更新最后登录时间
        DBUtil.update_last_login(user['user_id'])

        # 登录成功
        QMessageBox.information(self, "成功", f"欢迎回来，{username}！")
        self.login_success.emit(username, user['role'])
        self.accept()

    # 新增：显示注册窗口
    def show_register_dialog(self):
        """打开注册窗口"""
        self.register_dialog = RegisterDialog(self)
        self.register_dialog.register_success.connect(self.on_register_success)
        self.register_dialog.exec_()

    def on_register_success(self):
        """注册成功后的回调（清空输入框，方便用户直接登录）"""
        self.username_edit.clear()
        self.password_edit.clear()